package com.woniuxy.his.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniuxy.his.common.JwtUtils;
import com.woniuxy.his.common.Result;
import com.woniuxy.his.entity.Doctor;
import com.woniuxy.his.entity.User;
import com.woniuxy.his.mapper.DoctorMapper;
import com.woniuxy.his.service.ILoginService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.redisson.api.RedissonClient;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.Map;

@RestController
@CrossOrigin("*")
@Slf4j
public class LoginController {

    @Resource
    private ILoginService loginService;

    @Resource
    private RedissonClient redissonClient;

    @Resource
    private StringRedisTemplate stringredisTemplate;

    @Resource
    private DoctorMapper doctorMapper;

    @GetMapping("/login")
    public Result login(HttpServletResponse response, String username, String password) throws UnsupportedEncodingException, NoSuchAlgorithmException {
//        执行登录操作，签发jwt ,但不走shiro
        Result result = loginService.login(username, password);
        if(null!=result.getData()){

            User user = (User)result.getData();
            String jwt = JwtUtils.createJWT(user);

            response.setHeader(JwtUtils.AUTH_TOKEN_NAME,jwt);

            return Result.success("200","登录成功",jwt);
        }else if("密码错误".equals(result.getMessage())){
            return result.fail("400",result.getMessage(),null);
        }
        return Result.fail("400","无该用户",null);
    }


    @GetMapping("/getDoctorId")
    public Result getDoctorId(String username){
        log.info("username为{}",username);
        QueryWrapper<Doctor> wrapper = new QueryWrapper<>();
        wrapper.eq("username",username);
        Doctor doctor = doctorMapper.selectOne(wrapper);

        if(null!=doctor){
            return Result.success("200","找到医生di",doctor);
        }
        return Result.fail("400","未找到",null);


    }


    @GetMapping("/logout")
    public Result logout(HttpServletRequest httpServletRequest){
        log.info("注销用户id为的");
        String jwt = httpServletRequest.getHeader("jwt");
        return Result.success("200","退出成功",jwt);
    }


}
